All files / src/app/api/items/[id]/purge route.ts

93.75% Statements 15/16
100% Branches 4/4
100% Functions 1/1
93.33% Lines 14/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                5x                   11x 11x 11x 11x     11x 11x       7x 7x       7x 1x     6x   4x   2x      
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireAuth } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { requireApiItemCapability } from "@/server/dal/collection-access";
import { ItemPurgeService } from "@/server/services/ItemPurgeService";
import { errorResponse } from "@/server/api/http-errors";
 
const PurgeConfirmSchema = z.object({ confirm: z.literal("PURGE") });
 
// Permanent owner-only purge. Order matters for security: authenticate, resolve
// the item (including soft-deleted), gate as the COLLECTION OWNER, and ONLY THEN
// parse the confirm body. A non-owner with a malformed body must get 403, never a
// 400 that would leak body validity as an existence/permission oracle.
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id } = await params;
    const user = await requireAuth();
    const db = getDb();
 
    // items:purge = owner. includeDeleted: true — the item to purge may be soft-deleted.
    const item = await requireApiItemCapability(db, id, user.id, "items:purge", { includeDeleted: true });
    if (item instanceof NextResponse) return item; // 404 (absent) / 403 (not owner)
 
    // Authz passed — only now parse + validate the confirm body.
    let body: unknown;
    try {
      body = await request.json();
    } catch {
      return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
    }
    if (!PurgeConfirmSchema.safeParse(body).success) {
      return NextResponse.json({ error: "Confirmation required" }, { status: 400 });
    }
 
    await ItemPurgeService.fromDb(db).purge(item, user.id);
 
    return NextResponse.json({ message: "Item purged" });
  } catch (error) {
    return errorResponse(error);
  }
}